package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 200000)
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RecommendUserApi recommendUserApi;

    @Override
    public List<Visitors> queryVisitors(Long userId, int top) {
        // 第一次登陆：查询最近的5个访客记录  db.visitors.find({userId:1}).sort({date:-1})

        // 构造条件
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(top);
        // 查询
        return this.getVisitors(query);
    }

    @Override
    public List<Visitors> queryVisitors(Long userId, Long time) {
        // 第二次登陆：查询最近访客 db.visitors.find({userId:1,date:{$gt:100}}).sort({date:-1})

        // 构造条件
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("date").gt(time)
        );
        query.with(Sort.by(Sort.Order.desc("date")));
        // 查询
        return this.getVisitors(query);
    }


    /**
     * 抽取公用方法，查询最近访客、处理缘分值
     * @param query 查询条件
     * @return 返回设置缘分值后的最近访客
     */
    private List<Visitors> getVisitors(Query query) {
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        if (visitorsList != null) {
            for (Visitors visitors : visitorsList) {
                // 查询登陆用户与最近访客用户的缘分值
                Long score = recommendUserApi.queryScore(
                        visitors.getUserId(), visitors.getVisitorUserId());
                // 设置缘分值
                visitors.setScore(score.doubleValue());
            }
        }
        return visitorsList;
    }

}
